package com.xiashitech.agent.instrumentation.biz.api.increment.inst;

import com.xiashitech.agent.cache.status.CacheStatus;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.instrumentation.biz.api.increment.ApiIncrementHelper;
import com.xiashitech.agent.utils.DurationPrinter;
import io.opentelemetry.javaagent.bootstrap.CallDepth;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Context;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import org.apache.struts2.ServletActionContext;

import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.hasClassesNamed;
import static net.bytebuddy.matcher.ElementMatchers.isMethod;
import static net.bytebuddy.matcher.ElementMatchers.named;

public class XSApiIncrementStrutsnstrumentation implements TypeInstrumentation {

    @Override
    public ElementMatcher<ClassLoader> classLoaderOptimization() {
        return hasClassesNamed("com.opensymphony.xwork2.DefaultActionInvocation");
    }

    @Override
    public ElementMatcher<TypeDescription> typeMatcher() {
        return named("com.opensymphony.xwork2.DefaultActionInvocation");

    }

    @Override
    public void transform(TypeTransformer typeTransformer) {
        typeTransformer.applyAdviceToMethod(
                isMethod().and(named("invokeActionOnly")),
                this.getClass().getName() + "$ActionAdvice");
    }


    @SuppressWarnings("unused")
    public static class ActionAdvice {

        @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
        public static void onExit(@Advice.Local("otelCallDepth") CallDepth callDepth,
                                  @Advice.Local("otelContext") Context context) {
            DurationPrinter durationPrinter = new DurationPrinter("XSApiIncrementStrutsnstrumentation");
            try {
                if (CacheStatus.cannotRun()) {
                    return;
                }
                ApiIncrementHelper.syncIncrementApi(ServletActionContext.getRequest(),ServletActionContext.getResponse());
            } catch (Throwable e) {
                StartConfig.throwableStackPrinter(e);
            }
            durationPrinter.printElapseDuration("ActionAdvice e");
        }

    }

}
